package cn.edu.hpu.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.hpu.pojo.User;
import cn.edu.hpu.service.UserService;
import cn.edu.hpu.util.TimeUtil;

import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private UserService userService;
	private User user;
	private Map<String, Object> map;
	private List<User> ulist;
	private String id;
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	public String login(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String yanzhengma = request.getParameter("yanzhengma");
		if (SimpleImageCaptchaServlet.validateResponse(request, yanzhengma)) {
			User u = userService.findA(user);
			if (u != null && u.getPassword().equals(user.getPassword())) {
				map = ActionContext.getContext().getSession();
				map.put("user", u);
				return SUCCESS;
			}else{
				return LOGIN;
			}
		}else{
			return LOGIN;
		}
	}
	public String findAllUser(){
		ulist = userService.findAll();
		return SUCCESS;
	}
	public String saveadduser(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String yanzhengma = request.getParameter("yanzhengma");
		if (SimpleImageCaptchaServlet.validateResponse(request, yanzhengma)) {
				try {
					user.setCreatetime(TimeUtil.getTime());
					user.setEnable(true);
					userService.save(user);
					return SUCCESS;
				} catch (Exception e) {
					e.printStackTrace();
					return ERROR;
				}
		}else{
			return ERROR;
		}
	}
	public String leave(){
		Map<String, Object> map = ActionContext.getContext().getSession();
		map.remove("user");
		return SUCCESS;
	}
	
	//setter,getter
	
	public UserService getUserService() {
		return userService;
	}
	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public List<User> getUlist() {
		return ulist;
	}
	public void setUlist(List<User> ulist) {
		this.ulist = ulist;
	}
	public Map<String, Object> getMap() {
		return map;
	}
	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
